<?php

namespace app\admin\controller\pt;

use app\common\controller\Backend;
use app\common\library\Plan as PlanLib;
use app\admin\model\pt\JobPlan as PlanModel;
use app\admin\model\pt\Job as JobModel;
use app\admin\model\pt\Depart as DepartModel;
use app\admin\model\pt\DutyList as DutyModel;
use app\admin\model\pt\Labor as LaborModel;
use app\admin\model\pt\LaborAdmin as LaborAdminModel;
use app\admin\model\pt\Salary as SalaryModel;
use app\admin\library\Auth;
use Carbon\Carbon;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\common\library\Export as ExportLib;

/**
 * 岗位管理
 *
 * @icon fa fa-circle-o
 */
class Job extends Backend
{
    

    /**
     * Job模型对象
     * @var \app\admin\model\pt\Job
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\pt\Job;
        $this->view->assign("salaryModeList", $this->model->getSalaryModeList());
        $this->view->assign("roadList", $this->model->getIsRoadList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->with('depart')
                ->order($sort, $order)
                ->paginate($limit);

            $rows = $list->items();
            foreach ($rows as &$r) {
                $stage1 = '-';
                $stage2 = '-';
                if ($r['salary_mode'] == 'stage') {
                    $stage1 = $this->changeSalaryStage($r['labor1_salary_stage']);
                    $stage2 = $this->changeSalaryStage($r['labor2_salary_stage']);
                }
                $r['labor1_salary_stage'] = $stage1;
                $r['labor2_salary_stage'] = $stage2;
            }
            unset($r);

            $result = array("total" => $list->total(), "rows" => $rows);

            return json($result);
        }
        $laborModels = LaborModel::all();
        $labors = [];
        foreach ($laborModels as $labor) {
          $labors[] = [
              'id' => $labor->id,
              'name' => $labor->name,
          ];
        }
        $this->view->assign('labors', json_encode($labors));
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $laborModels = LaborModel::all();
        $labors = [];
        foreach ($laborModels as $labor) {
          $labors[] = [
              'id' => $labor->id,
              'name' => $labor->name,
          ];
        }
        $this->view->assign('labors', $labors);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $laborModels = LaborModel::all();
        $labors = [];
        foreach ($laborModels as $labor) {
          $labors[] = [
              'id' => $labor->id,
              'name' => $labor->name,
          ];
        }
        $this->view->assign('labors', $labors);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function copy($ids = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $laborModels = LaborModel::all();
        $labors = [];
        foreach ($laborModels as $labor) {
          $labors[] = [
              'id' => $labor->id,
              'name' => $labor->name,
          ];
        }
        $this->view->assign('labors', $labors);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function arrange()
    {
        $jobId = $this->request->get('id');
        $row = [];
        $row['job_id'] = $jobId;
        $this->view->assign('row', $row);
        return $this->view->fetch(); 
    }

    public function loadPlan()
    {
        if ($this->request->isPost()) {
            $data = [];
            $date = $this->request->post('date', '');
            $jobId = $this->request->post('jobId', 0);
            if (!empty($jobId)) {
                $date = empty($date) ? date('Y-m-d') : $date;
                $month = date('Ym', strtotime($date));
                $planModel = new PlanModel();
                $plans = $planModel->where('pt_job_id', $jobId)->where('date_id', 'like', $month . '%')->select();
                $arr = [];
                foreach ($plans as $p) {
                    $tmp = [
                        'date' => date('Y-m-d', strtotime($p->date_id)),
                        'type' => 'common',
                        'content' => $p->consume_total . "/" . $p->plan_total,
                    ];
                    $arr[$p->date_id] = $tmp;
                }
                // 循环当月
                $startDate = $month . "01";
                $endDate = $month . "31";
                for ($dateId = $startDate; $dateId <= $endDate; $dateId++) {
                    $tmp = [
                        'date' => date('Y-m-d', strtotime($dateId)),
                        'type' => 'common',
                        'content' => "0/0",
                    ];
                    if (isset($arr[$dateId])) {
                        $tmp = $arr[$dateId];
                    }
                    $data[] = $tmp;
                }
            }
            $this->success('获取成功', '', $data);
        }
    }

    public function handlePlanDay()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $jobId = $params['jobId'];
                $startDate = $params['startDate'];
                $endDate = $params['endDate'];
                $planTotal = $params['planTotal'];
                if (empty($jobId) || empty($planTotal) || empty($startDate) || empty($endDate)) {
                    $this->error('参数不完整');
                }
                $result = false;
                Db::startTrans();
                try {
                    $planLib = new PlanLib();    
                    $planLib->handleJobPlan($startDate, $endDate, $jobId, $planTotal);
                    $result = true;
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->error(__('need post'));
    }

    public function ajaxJob()
    {
        $departId = $this->request->get('departId', '');
        $where = ['status' => 'normal'];
        $list = null;
        if (empty($departId)) {
            // 查询到所有部门 
            $list = Db::name('pt_depart')->where($where)->field('id as value,name')->order('id asc')->select();
        } else {
            $where['pt_depart_id'] = $departId;
            $list = Db::name('pt_job')->where($where)->field('id as value,name')->order('id asc')->select();
        }

        $this->success('', '', $list);
    }

    public function statistic()
    {
        // 查询所有部门
        $curMonthCarbon = Carbon::parse(date('Y-m-d'));
        
        $startDay = $curMonthCarbon->firstOfMonth()->toDateString();
        $lastDay = $curMonthCarbon->lastOfMonth()->toDateString();
        $startDateId = date('Ymd');
        $endDateId = date('');
        $allDeparts = DepartModel::where('status', 'normal')->select();
        $tables = [];
        $tablesSn = [];
        $departIds = [];
        foreach ($allDeparts as $d) {
            $tmp = [
                'id' => $d->id . "-" . $dateId,
                'name' => $d->name,
            ];
            $tables[] = $tmp;
            $tablesSn[] = $d->id . "-" . $dateId;
            $departIds[] = $d->id;
        }
        // 查出总计
        $jobIds = [];
        $jobs = JobModel::where('status', 'normal')->where('pt_depart_id', 'in', $departIds)->select();
        foreach ($jobs as $j) {
            $jobIds[] = $j->id;
        }

        $plans = PlanModel::where('pt_job_id', 'in', $jobIds)->where('date_id', $dateId)->select();
        $planTotal = 0;
        $consumeTotal = 0;
        foreach ($plans as $p) {
            $planTotal += $p->plan_total;
            $consumeTotal += $p->consume_total;
        }
        $this->view->assign('plan_total', $planTotal);
        $this->view->assign('consume_total', $consumeTotal);
        $this->view->assign('tables', $tables);
        $this->view->assign('tablesSn', json_encode($tablesSn));
        $this->view->assign('query_date', date('Y-m-d', strtotime($dateId)));
        return $this->view->fetch(); 
    
    }

    public function global_job()
    {
        // 查询所有部门
        $dateId = date('Ymd');
        if ($this->request->isAjax()) {
            $dateId = date('Ymd', strtotime($this->request->get('query_date')));
        }
        $allDeparts = DepartModel::where('status', 'normal')->select();
        $tables = [];
        $tablesSn = [];
        $departIds = [];
        foreach ($allDeparts as $d) {
            $tmp = [
                'id' => $d->id . "-" . $dateId,
                'name' => $d->name,
            ];
            $tables[] = $tmp;
            $tablesSn[] = $d->id . "-" . $dateId;
            $departIds[] = $d->id;
        }

        // 查出总计
        $jobIds = [];
        $jobs = JobModel::where('status', 'normal')->where('pt_depart_id', 'in', $departIds)->select();
        foreach ($jobs as $j) {
            $jobIds[] = $j->id;
        }

        $plans = PlanModel::where('pt_job_id', 'in', $jobIds)->where('date_id', $dateId)->select();
        $planTotal = 0;
        $consumeTotal = 0;
        foreach ($plans as $p) {
            $planTotal += $p->plan_total;
            $consumeTotal += $p->consume_total;
        }

        if ($this->request->isAjax()) {
            $data = ['plan_total' => $planTotal, 'consume_total' => $consumeTotal];
            $this->success('获取成功', '', $data);
        }
        $this->view->assign('plan_total', $planTotal);
        $this->view->assign('consume_total', $consumeTotal);
        $this->view->assign('tables', $tables);
        $this->view->assign('tablesSn', json_encode($tablesSn));
        $this->view->assign('query_date', date('Y-m-d', strtotime($dateId)));
        return $this->view->fetch(); 
    }

    public function jobs()
    {
        $result = array("total" => 0, "rows" => []);
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $auth = Auth::instance();
            $adminName = $auth->isLogin() ? $auth->username : __('Unknown');
            $adminId = $auth->isLogin() ? $auth->id : 0;
            // 查找是否劳务公司
            $laborAdmin = LaborAdminModel::where('admin_id', $adminId)->find();
            $laborId = 0;
            if ($laborAdmin) {
                $laborId = $laborAdmin->pt_labor_id;
            }

            $params = explode("-", $this->request->get('id'));
            $departId = $params[0];
            $dateId = date('Ymd', strtotime($this->request->get('query_date', $params[1])));
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $jobIds = [];
            $jobInfo = [];
            $jobs = JobModel::where('status', 'normal')->where('pt_depart_id', $departId)->select();
            foreach ($jobs as $j) {
                $jobIds[] = $j->id;
                $jobInfo[$j->id] = $j->name;
            }

            $plans = PlanModel::where('pt_job_id', 'in', $jobIds)->where('date_id', $dateId)->select();
            $data = [];
            foreach ($plans as $p) {
                $tmp = [
                    'id'  => $p->pt_job_id . "_" . date('Y-m-d', strtotime($dateId)),
                    'job_name' => isset($jobInfo[$p->pt_job_id]) ? $jobInfo[$p->pt_job_id] : '-',
                    'plan_total' => $p->plan_total,
                    'consume_total' => $p->consume_total,
                    'job_id' => $p->pt_job_id,
                    'cur_date' => date('Y-m-d', strtotime($dateId)),
                    'persons' => [],
                ];
                $data[] = $tmp;
            }
            $persons = [];
            $dutyList = DutyModel::where('pt_job_id', 'in', $jobIds)->where('date_id', $dateId);
            $dutyList = $dutyList->with('person')->select();
            foreach ($dutyList as $duty) {
                if ($laborId) {
                    if ($duty->person->pt_labor_id == $laborId) {
                        $persons[$duty->pt_job_id . "_" . date('Y-m-d', strtotime($dateId))][] = [
                            'name' => !empty($duty->person) ? $duty->person->user_name : '-',
                            'phone' => !empty($duty->person) ? $duty->person->phone : '-',
                        ];
                    }
                } else {
                    $persons[$duty->pt_job_id . "_" . date('Y-m-d', strtotime($dateId))][] = [
                        'name' => !empty($duty->person) ? $duty->person->user_name : '-',
                        'phone' => !empty($duty->person) ? $duty->person->phone : '-',
                    ];
                }
            }
            foreach ($data as &$d) {
                if (isset($persons[$d['id']])) {
                    $d['persons'] = $persons[$d['id']];
                }
            }
            unset($d);

            $result = array("total" => count($data), "rows" => $data);
        }

        return json($result);
    
    }

    public function export()
    {
        $auth = Auth::instance();
        $adminName = $auth->isLogin() ? $auth->username : __('Unknown');
        $adminId = $auth->isLogin() ? $auth->id : 0;
        // 查找是否劳务公司
        $laborAdmin = LaborAdminModel::where('admin_id', $adminId)->find();
        $laborId = 0;
        if ($laborAdmin) {
            $laborId = $laborAdmin->pt_labor_id;
        }
        $dateId = date('Ymd', strtotime($this->request->get('query_date')));

        $allDeparts = DepartModel::where('status', 'normal')->select();
        $departs = [];
        $departIds = [];
        foreach ($allDeparts as $d) {
            $tmp = [
                'id' => $d->id,
                'name' => $d->name,
            ];
            $departs[$d->id] = $d->name;
            $departIds[] = $d->id;
        }

        $jobIds = [];
        $jobInfo = [];
        $jobs = JobModel::where('status', 'normal')->where('pt_depart_id', 'in', $departIds)->select();
        foreach ($jobs as $j) {
            $jobIds[] = $j->id;
            $jobInfo[$j->id] = $j->name;
        }
        
        // 查找所有人员
        $persons = [];
        $dutyList = DutyModel::where('pt_job_id', 'in', $jobIds)->where('date_id', $dateId);
        $dutyList = $dutyList->with('person')->select();
        foreach ($dutyList as $duty) {
            $jobName = isset($jobInfo[$duty->pt_job_id]) ? $jobInfo[$duty->pt_job_id] : '未知岗位';
            $departName = isset($departs[$duty->pt_depart_id]) ? $departs[$duty->pt_depart_id] : '未知部门';

            if ($laborId) {
                if ($duty->person->pt_labor_id == $laborId) {
                    $persons[] = [
                        $departName,
                        $jobName,
                        !empty($duty->person) ? $duty->person->user_name : '-',
                        !empty($duty->person) ? $duty->person->phone : '-',
                    ];
                }
            } else {
                $persons[] = [
                    $departName,
                    $jobName,
                    !empty($duty->person) ? $duty->person->user_name : '-',
                    !empty($duty->person) ? $duty->person->phone : '-',
                ];
            }
        }

        $savePath = '/uploads/export/'.date('Ymd') ;
        $filename =  $dateId .'(人员安排计划)_' . uniqid() .'.xlsx';
        $filePath = ROOT_PATH . 'public' . $savePath;
        $fileSaveName =  $filePath  . '/' . $filename;
        if (!is_dir($filePath)) {
            @mkdir($filePath, 0755, true);
        }
        $headers = [
            '部门名称',
            '岗位名称',
            '人员姓名',
            '联系方式',
        ];
        $exportLib = new ExportLib($headers, $persons, $fileSaveName, 'save');
        $exportLib->createTable();
        $this->success('导出成功', '', ['file' => cdnurl($savePath . '/' .$filename, true)]);
    
    }

    public function global_fee()
    {
        // 查询所有部门
        $dateId = date('Ymd');
        /*
        if ($this->request->isAjax()) {
            $dateId = date('Ymd', strtotime($this->request->get('query_date')));
        }
        */
        $allDeparts = DepartModel::where('status', 'normal')->select();
        $tables = [];
        $tablesSn = [];
        $departIds = [];
        foreach ($allDeparts as $d) {
            $tmp = [
                'id' => $d->id . "-" . $dateId,
                'name' => $d->name,
            ];
            $tables[] = $tmp;
            $tablesSn[] = $d->id . "-" . $dateId;
            $departIds[] = $d->id;
        }
        /*
        // 查出总计
        $jobIds = [];
        $jobs = JobModel::where('status', 'normal')->where('pt_depart_id', 'in', $departIds)->select();
        foreach ($jobs as $j) {
            $jobIds[] = $j->id;
        }

        $plans = PlanModel::where('pt_job_id', 'in', $jobIds)->where('date_id', $dateId)->select();
        $planTotal = 0;
        $consumeTotal = 0;
        foreach ($plans as $p) {
            $planTotal += $p->plan_total;
            $consumeTotal += $p->consume_total;
        }

        if ($this->request->isAjax()) {
            $data = ['plan_total' => $planTotal, 'consume_total' => $consumeTotal];
            $this->success('获取成功', '', $data);
        }
        */
        // $this->view->assign('plan_total', $planTotal);
        // $this->view->assign('consume_total', $consumeTotal);
        $this->view->assign('tables', $tables);
        $this->view->assign('tablesSn', json_encode($tablesSn));
        $this->view->assign('query_date', date('Y-m-d', strtotime($dateId)));
        return $this->view->fetch(); 
    
    }

    public function fees()
    {
        $result = array("total" => 0, "rows" => []);
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $auth = Auth::instance();
            $adminName = $auth->isLogin() ? $auth->username : __('Unknown');
            $adminId = $auth->isLogin() ? $auth->id : 0;
            // 查找是否劳务公司
            $laborAdmin = LaborAdminModel::where('admin_id', $adminId)->find();
            $laborId = 0;
            if ($laborAdmin) {
                $laborId = $laborAdmin->pt_labor_id;
            }

            $params = explode("-", $this->request->get('id'));
            $departId = $params[0];
            $dateId = date('Ymd', strtotime($this->request->get('query_date', $params[1])));
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $jobIds = [];
            $jobInfo = [];
            $jobs = JobModel::where('status', 'normal')->where('pt_depart_id', $departId)->select();
            foreach ($jobs as $j) {
                $jobIds[] = $j->id;

                $tmp = [
                    'job_name' => $j->name,
                    'total_fee' => 0,
                    'consume_total' => 0,
                    'intern_total' => 0,
                    'parttime_total' => 0,
                ];
                $jobInfo[$j->id] = $tmp;
            }

            $salarys = SalaryModel::where('pt_job_id', 'in', $jobIds)->where('date_id', $dateId)->with('person')->select();

            foreach ($salarys as $s) {
                if ($jobInfo[$s->pt_job_id]) {
                    if ($s->is_cal) {
                        $jobInfo[$s->pt_job_id]['total_fee'] += $s->salary_total;
                    }
                    $jobInfo[$s->pt_job_id]['consume_total']++;
                    if ($s->person->user_type == 'intern') {
                        $jobInfo[$s->pt_job_id]['intern_total']++;
                    } else {
                        $jobInfo[$s->pt_job_id]['parttime_total']++;
                    }
                }
            }
            $data = [];
            foreach ($jobInfo as $jobId => $job) {
                $data[] = $job;
            }

            $result = array("total" => count($data), "rows" => $data);
        }

        return json($result);
    
    }

    public function clockIndex()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $jobId = $this->request->get('job_id');
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $jobModel = $this->model->get($jobId);
            $clockLngLats = $jobModel->clock_lnglats;
            $rows = [];
            if (!empty($clockLngLats)) {
               $rows = json_decode($clockLngLats, true) ;
            }

            $result = array("total" => count($rows), "rows" => $rows);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function clockAdd()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    $jobModel = $this->model->get($params['job_id']);
                    $lnglatJson = $jobModel->clock_lnglats;
                    $lnglatArr = [];
                    $lnglat = [];
                    if (!empty($lnglatJson)) {
                        $lnglatArr = json_decode($lnglatJson, true);
                        if (count($lnglatArr) >= 3) {
                            throw new Exception('至多只能添加3个打卡点');
                        }
                    }
                    if (!empty($lnglatArr)) {
                        array_multisort(array_column($lnglatArr,'id'),SORT_ASC,$lnglatArr);
                        $lastId = $lnglatArr[count($lnglatArr) - 1]['id'];
                        $id = $lastId + 1;
                    } else {
                        $id = 1;
                    }
                    $lnglat = [
                        'id' => $id,
                        'address' => $params['address'],
                        'lng' => $params['lng'],
                        'lat' => $params['lat'],
                        'radius' => $params['radius'],
                    ];
                    $lnglatArr[] = $lnglat; 
                    $jobModel->clock_lnglats = json_encode($lnglatArr);
                    $jobModel->save();
                    $result = true;
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign('jobId', $this->request->get('job_id'));
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function clockEdit($ids = null)
    {
        
        $jobId = $this->request->get('job_id');
        $jobModel = $this->model->get($jobId);
        $lnglatJson = $jobModel->clock_lnglats;
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $ids = $this->request->get('ids');
            if ($params) {
                $result = false;
                Db::startTrans();
                try {
                    $lnglatArr = [];
                    $lnglat = [
                        'id' => $ids,
                        'address' => $params['address'],
                        'lng' => $params['lng'],
                        'lat' => $params['lat'],
                        'radius' => $params['radius'],
                    ];
                    if (!empty($lnglatJson)) {
                        $lnglatArr = json_decode($lnglatJson, true);
                        $newArr = [];
                        foreach ($lnglatArr as $r) {
                            if ($r['id'] == $ids) {
                                $r = $lnglat;
                            }
                            $newArr[] = $r;
                        }
                    }
                    $jobModel->clock_lnglats = json_encode($newArr);
                    $jobModel->save();
                    $result = true;
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $lnglatArr = json_decode($lnglatJson, true);
        $row = [];
        foreach ($lnglatArr as $a) {
            if ($a['id'] == $ids) {
                $row = $a;
            }
        }
        $this->view->assign('jobId', $jobId);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function clockDel($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $jobId = $this->request->get('job_id');
            $count = 0;
            Db::startTrans();
            try {
                $count = 1;
                $jobModel = $this->model->get($jobId);
                $lnglatJson = $jobModel->clock_lnglats;
                $lnglatArr = json_decode($lnglatJson, true);
                $newArr = [];
                foreach ($lnglatArr as $a) {
                    if ($a['id'] != $ids) {
                        $newArr[] = $a;
                    }
                }
                $jobModel->clock_lnglats = json_encode($newArr);
                $jobModel->save();
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }



    private function changeSalaryStage($salaryStage)
    {
        $arr = json_decode($salaryStage, true);
        $stage = '';
        if (empty($arr)) {
            $stage = '未设置';
        } else {
            foreach ($arr as $a) {
                $stage .= "起始：" . $a['start'] . ", 结束：" . $a['end'] . ", 工资：" . $a['salary'] . "<br />";
            }
        }

        return $stage;
    }

}
